package shuaige.jdk.多线程.锁.可重入锁;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Condition_条件使用示例3 {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private Queue<String> queue = new LinkedList<>();

    public static void main(String[] args) throws InterruptedException {
        var taskQueue = new Condition_条件使用示例3();
        var threadList = new ArrayList<Thread>();
        for (int i = 0; i < 5; i++) {
            // 执行一个线程
            var t = new Thread() {
                @Override
                public void run() {
                    // 执行task:
                    while (true) {
                        try {
                            String s = taskQueue.getTask();
                            System.out.println("execute getTask: " + s);
                        } catch (InterruptedException e) {
                            return;
                        }
                    }
                }
            };
            System.out.println("启动线程，执行：getTask()");
            threadList.add(t);
            t.start();
        }
        System.out.println("---------------getTask启动完成-----------------");
        var add = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                // 放入task:
                String s = "t-" + Math.random();
                System.out.println("add task: " + s);
                taskQueue.addTask(s);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.out.println("InterruptedException");
                }
            }
        });
        add.start();
        add.join();
        Thread.sleep(100);
        for (var t : threadList) {
            System.out.println("中断线程：" + t.getName());
            t.interrupt();
        }

    }

    public void addTask(String s) {
        lock.lock();
        try {
            queue.add(s);
            // 唤醒所有等待的线程
            condition.signalAll();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    public String getTask() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                // 使当前线程等待，直到它收到信号或被中断。
                condition.await();
            }
            return queue.remove();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

}
